package com.metadata_system.common.service;

import com.metadata_system.common.db.entity.User;
import com.metadata_system.common.db.entity.UserLoginLog;
import com.metadata_system.common.db.mapper.UserLoginLogMapper;
import com.metadata_system.common.db.mapper.UserMapper;
import com.metadata_system.common.dto.ApiResult;
import com.metadata_system.common.http.request_dto.UserLoginRequest;
import com.metadata_system.common.request.UserLoginLogListParams;
import com.metadata_system.common.utils.DateTimeUtil;
import com.metadata_system.system.response.UserLoginLogResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author safi
 * @date 2019年10月9日20:30:57
 */
@Slf4j
@Service
public class UserLoginLogService{
	@Autowired(required = false)
	UserLoginLogMapper userLoginLogMapper;
	@Autowired(required = false)
	UserMapper userMapper;

	// 允许每日密码最大错误次数(自然日)
	@Value("${metadata-system.limit-daliy-login-max-error-nums:10}")
	private int limitDaliyLoginMaxErrorNums = 10;
	@Autowired(required = false)
	CommonUserService commonUserService;

	// 检查-今日错误次数
	public ApiResult checkErrorNums(UserLoginRequest request,Date unLockLoginTime) {
		Example example = new Example(UserLoginLog.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", request.getUserId());
		criteria.andEqualTo("status", 0);

		// 如果解锁后，则按照解锁时间往后推，开始查看错误次数
		if (unLockLoginTime!=null){
			criteria.andGreaterThan("unLockLoginTime", unLockLoginTime);
		}

		try {
			String dateString = DateTimeUtil.formatDateTimetoString(new Date(), "yyyy-MM-dd") + " 00:00:00";
			criteria.andGreaterThan("createdTime", dateString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		int count = this.userLoginLogMapper.selectCountByExample(example);
		if (this.limitDaliyLoginMaxErrorNums < count) {
			User user = this.userMapper.selectByPrimaryKey(request.getUserId());
			return ApiResult.error("错误次数已经达到最大次数: " + this.limitDaliyLoginMaxErrorNums);
		}
		return ApiResult.success("");
	}

	// 插入-新日志

	public void add(UserLoginRequest request) {
		UserLoginLog userLoginLog = UserLoginLog.builder()
				.userId(request.getUserId())
				.username(request.getUsername())
				.ip(request.getIp())
				.role(request.getRole())
				.deviceId(request.getDeviceId())
				.status(request.getStatus())
				.createdTime(new Date())
				.build();
		this.userLoginLogMapper.insert(userLoginLog);
	}



	// 清空-用户今日错误日志

	public void clearLoginError(Integer userId) {
		Example example = new Example(UserLoginLog.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", userId);
		criteria.andEqualTo("status", 0);

		try {
			String dateString = DateTimeUtil.formatDateTimetoString(new Date(), "yyyy-MM-dd") + " 00:00:00";
			criteria.andGreaterThan("createdTime", dateString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 更新用户错误状态
		this.userLoginLogMapper.updateByExampleSelective(UserLoginLog.builder().status(1).build(), example);
	}

	/**
	 * 登录日志-列表
	 */
	@SneakyThrows
	public ApiResult getList(UserLoginLogListParams listParams) {
		Example example = new Example(UserLoginLog.class);
		Example.Criteria criteria = example.createCriteria();

		if (listParams.getCurrRole()!=null && listParams.getCurrRole().equals("System")) {
			criteria.andEqualTo("role", "User");
		}

		// 1.查询条件参数
		// 1-2.普通查询参数
		if (listParams.getUserId()!=null){
			criteria.andEqualTo("userId", listParams.getUserId());
		}
		if (!StringUtils.isBlank(listParams.getRole())) {
			criteria.andEqualTo("role", listParams.getRole());
		}
		if (!StringUtils.isBlank(listParams.getUsername())) {
			criteria.andLike("username", "%"+listParams.getUsername()+"%");
		}
		if (!StringUtils.isBlank(listParams.getDeviceId())) {
			criteria.andLike("deviceId", "%"+listParams.getDeviceId()+"%");
		}
		if (!StringUtils.isBlank(listParams.getIp())) {
			criteria.andLike("ip", "%"+listParams.getIp()+"%");
		}
		if (listParams.getStatus()!=null){
			criteria.andEqualTo("status", listParams.getStatus());
		}
		if (!CollectionUtils.isEmpty(listParams.getUserIdList())){
			criteria.andIn("userId", listParams.getUserIdList());
		}

		listParams.setConditionTime(listParams.getCreatedTime(),criteria,"createdTime");
		listParams.setOrder(example,"createdTime,id");

		// 3.查询: 总条数,列表数据
		int total = this.userLoginLogMapper.selectCountByExample(example);
		List<UserLoginLog> userLoginLogs = new ArrayList<>();
		if (total > 0) {
			userLoginLogs = this.userLoginLogMapper.selectByExampleAndRowBounds(example, listParams.getRowRunds());
		}
		return ApiResult.successPage(UserLoginLogResponse.formatData(userLoginLogs), total);
	}
}


